﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace psafth.RCTiming.Main.Pages.Dialogs
{
    /// <summary>
    /// Interaction logic for AddTransponderDialog.xaml
    /// </summary>
    public partial class AddTransponderDialog : Window
    {
        private Driver _driver = null;
        private UserPage _userPage = null;

        public DBContext DbContext
        {
            get
            {
                return this._userPage.MainWindow.DbContext;
            }
            set
            {
                this._userPage.MainWindow.DbContext = value;
            }
        }

        public AddTransponderDialog(Driver d, UserPage up)
        {
            _driver = d;
            _userPage = up;
            InitializeComponent();

            tbTransponderId.Focus();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            int transponderId;

            try
            {
                if (Int32.TryParse(tbTransponderId.Text.Trim(), out transponderId))
                {
                    Transponder foundTransponder;

                    foundTransponder = DbContext.Transponders.FirstOrDefault(t => t.TransponderId == transponderId);

                    if (foundTransponder != null)
                    {
                        System.Windows.MessageBox.Show(string.Format("Transponder med id {0} tillhör redan {1}[{2}]", transponderId, foundTransponder.Driver.FullName, foundTransponder.Driver.LicenceNumber), "Fel", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);
                        tbTransponderId.Text = string.Empty;
                    }
                    else
                    {
                        DbContext.Drivers.FirstOrDefault(d => d.Id == _driver.Id).Transponders.Add(new Transponder() { TransponderId = transponderId });
                        DbContext.SaveChanges();

                        _userPage.UpdateTransponderListBox();
                        this.Close();
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("TransponderId kan enbart innehålla siffror", "Fel", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);
                    tbTransponderId.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
